import _ from 'lodash';

import {
    GET_ALL_MENU,
    GET_ALL_MENU_SUCCESS,
    UPDATE_NAVPATH
} from '../actions/menu';

const initialState = {
  items: [],
  navpath: []
};

export default function menu(state = initialState, action = {}) {
  switch (action.type) {
    // 取得所有菜单数据
    case GET_ALL_MENU_SUCCESS:
      return Object.assign({}, initialState, {items: action.payload.data});
    // 修改当前页面访问的地址
    case UPDATE_NAVPATH:
      // 现在返回重要的值
      let navpath = [], tmpOb1,tmpOb2,tmpOb3,tmpKey1,tmpKey2,tmpKey3;
      if(Array.isArray(action.payload.data)){
        action.payload.data.reverse().map((item)=>{
          // 一级菜单
          if(item.indexOf('bar_menu') != -1){
            tmpKey1 = item.replace('bar_menu', '');
            tmpOb1 = _.find(state.items, function(o) {
              return o.key == tmpKey1;
            });
            navpath.push({
              key: tmpOb1.key,
              name: tmpOb1.name
            })
          }
          
          // 二级菜单
          if(item.indexOf('sub1_menu') != -1){
            tmpKey2 = item.replace('sub1_menu', '');
            tmpOb2 = _.find(tmpOb1.child, function(o) {
              return o.key == tmpKey2;
            });
            navpath.push({
              key: tmpOb2.key,
              name: tmpOb2.name
            })
          }

          // 三级菜单
          if(item.indexOf('sub2_menu') != -1){
            tmpKey3 = item.replace('sub2_menu', '');
            tmpOb3 = _.find(tmpOb2.child, function(o) {
              return o.key == tmpKey3;
            });
            navpath.push({
              key: tmpOb3.key,
              name: tmpOb3.name
            })
          } 
        })
      }

      return Object.assign({}, state, {
        currentIndex: action.payload.key*1,
        navpath: navpath,
        main_menu_index: action.payload.index
      });
    default:
      return state;
  }
}
